package com.framework.network.utils

import android.annotation.TargetApi
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkInfo
import android.os.Build

/**
 * @ClassName: NetworkUtil
 * @Description: 网络判断工具类
 * @Author: you
 */
object NetworkUtil {

    /**
     * 判断当前网络是否可用
     */
    fun isNetworkAvailable(context: Context): Boolean {
        val info = getActiveNetworkInfo(context) ?: return false
        return info.isConnected
    }

    /**
     * 判断当前是否在Wifi状态下
     */
    fun isWifi(context: Context): Boolean {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            val ability = getNetworkCapability(context) ?: return false
            return ability.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        } else {
            val info = getActiveNetworkInfo(context) ?: return false
            return info.type == ConnectivityManager.TYPE_WIFI
        }
    }

    /**
     * 判断当前是否不再Wifi状态下
     */
    fun isMobile(context: Context): Boolean {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            val ability = getNetworkCapability(context) ?: return false
            return ability.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
        } else {
            val info = getActiveNetworkInfo(context) ?: return false
            return info.type == ConnectivityManager.TYPE_MOBILE
        }
    }

    /**
     * 获取当前网络连接信息
     */
    private fun getActiveNetworkInfo(context: Context): NetworkInfo? {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
        return cm?.activeNetworkInfo
    }

    /**
     * 获取当前网络状态信息
     */
    @TargetApi(Build.VERSION_CODES.M)
    private fun getNetworkCapability(context: Context): NetworkCapabilities? {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return null
        val network = cm.activeNetwork ?: return null
        return cm.getNetworkCapabilities(network)
    }


}